package com.weavernorth.action.zxkDataToV8;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.general.Util;
import com.weavernorth.util.Logger4jUtil;
import org.apache.log4j.Logger;
import weaver.common.util.string.StringUtil;
import weaver.conn.ConnectionPool;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Date;

import static com.weavernorth.util.HttpUtil.doPost;
import static com.weavernorth.util.MD5Util.md5Encryption;

/**
 * @Author: bruseewang
 * @Package: com.weavernorth.action.zxkDataToV8
 * @date: 2021/11/19 11:16
 * @description: 将【品牌】尊享卡延期申请流程中需要延期的卡号传至V8,并将V8返回的数据回写到表中
 */
public class zxkDataToV8 implements Action {
    public static ConnectionPool pool = ConnectionPool.getInstance();
    public Connection conn;
    public Statement statement;

    @Override
    public String execute(RequestInfo requestInfo) {
        Logger log = Logger4jUtil.getLoggerByName("/action/zxkDataToV8/");
        BaseBean bb = new BaseBean();
        log.info("尊享卡延期接口数据传V8-begin=======>");
        //请求id
        String strRequestid = requestInfo.getRequestid();
        log.info("流程requestid=" + strRequestid);
        String strTable = requestInfo.getRequestManager().getBillTableName();
        log.info("表名：" + strTable);
        String strQuery = "SELECT a.requestid,a.czlx,b.* FROM " + strTable + " a INNER JOIN " + strTable + "_dt1 b ON a.id=b.mainid WHERE a.requestid='" + strRequestid + "'";
        RecordSet rs = new RecordSet();
        rs.execute(strQuery);
        String zxkh = "";//尊享卡号
        String czlx = "";//操作类型：0:查询，1：更新
        String strMainid = "";
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonParam;
        while (rs.next()) {
            if ("".equals(strMainid)) {
                strMainid = Util.null2String(rs.getString("mainid"));//主表id
            }
            zxkh = Util.null2String(rs.getString("kh"));//卡号
            czlx = Util.null2String(rs.getString("czlx"));//操作类型
            log.info("操作类型："+czlx);
            jsonParam = new JSONObject();
            jsonParam.put("djqhm", zxkh);//代金券号(尊享卡号)
            jsonParam.put("djyxrq", "");//日期
            jsonParam.put("sjffrq", "");//日期
            if(czlx.equals("0")){
                jsonParam.put("stype", "Q");//操作类型
            }else {
                jsonParam.put("stype", "U");//操作类型
            }

            jsonArray.add(jsonParam);
        }
        log.info("请求json：" + jsonArray);
        if (jsonArray.size() > 0) {
            //V8接口外网地址：http://58.18.34.23:18084/FY_TP_SERVICE/FY_BPM_SERVICE.json?
            String strUrl = Util.null2String(bb.getPropValue("cxfaFromV8", "zxk_url"));
            String sapId = "sapbpm";
            String strS = sapId + jsonArray.toJSONString();
            log.info("md5要加密的字符串：" + strS);
            //sign=Md5(appId+data)
            String strSign = null;
            try {
                strSign = md5Encryption(strS);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("md5加密异常：" + e.toString());
            }
            log.info("md5加密后的字符串：" + strSign.toUpperCase());
            strUrl = strUrl + strSign.toUpperCase();
            log.info("接口请求地址：" + strUrl);
            String strResponse = null;
            try {
                strResponse = doPost(strUrl, jsonArray.toJSONString());
                log.info("V8接口返回值：" + strResponse);
                if (StringUtil.isNotNullAndEmpty(strResponse)) {
                    JSONObject jsonObject = JSONObject.parseObject(strResponse);
                    String requestNo = jsonObject.getString("requestNo");
                    log.info("requestNo：" + requestNo);
                    String result = jsonObject.getString("success");
                    log.info("result：" + result);
                    String message = jsonObject.getString("errorMessage");
                    log.info("message：" + message);
                    String data = jsonObject.getString("data");
                    String s_msg = "";
                    String s_id = "";
                    String s_update = "";
                    String e_msg = "";
                    String e_id = "";
                    String e_update = "";
                    if (StringUtil.isNotNullAndEmpty(data)) {
                        JSONObject resultData = JSONObject.parseObject(data);
                        //处理成功的数据
                        JSONArray succList = resultData.getJSONArray("succList");
                        log.info("V8处理成功的数据：" + succList);
                        //处理失败的数据
                        JSONArray errList = resultData.getJSONArray("errList");
                        log.info("V8处理失败的数据：" + errList);
                        log.info("操作类型："+czlx);
                        if ("1".equals(czlx)) {
                            log.info("更新");
                            conn = pool.getConnection();
                            statement = conn.createStatement();
                            if (succList.size() > 0) {
                                for (int i = 0; i < succList.size(); i++) {
                                    JSONObject success = succList.getJSONObject(i);
                                    s_msg = success.getString("errMsg");
                                    s_id = success.getString("id");
                                    s_update = "update " + strTable + "_dt1 set cljg='" + s_msg + "' where mainid='" + strMainid + "' and kh='" + s_id + "'";
                                    log.info("处理成功的更新sql：" + s_update);
                                    statement.addBatch(s_update);
                                }
                            }
                            if (errList.size() > 0) {
                                for (int i = 0; i < errList.size(); i++) {
                                    JSONObject errObj = errList.getJSONObject(i);
                                    e_msg = errObj.getString("errMsg");
                                    e_id = errObj.getString("id");
                                    e_update = "update " + strTable + "_dt1 set cljg='" + e_msg + "' where mainid='" + strMainid + "' and kh='" + e_id + "'";
                                    log.info("处理失败的更新sql：" + e_update);
                                    statement.addBatch(e_update);
                                }
                            }
                            Long begin1 = System.currentTimeMillis();
                            statement.executeBatch();
                            Long end1 = System.currentTimeMillis();
                            log.info("批量更新耗时：" + (end1 - begin1) + "(毫秒)");
                            conn.close();
                            statement.close();
                        } else {
                            //操作类型为查询时,只要有报错信息就阻止提交
                            if (errList.size() > 0) {
                                StringBuilder mes_sb=new StringBuilder();
                                for (int i = 0; i < errList.size(); i++) {
                                    JSONObject errObj = errList.getJSONObject(i);
                                    e_msg = errObj.getString("errMsg");
                                    e_id = errObj.getString("id");
                                    mes_sb.append("卡号："+e_id+",错误信息："+e_msg+";");
                                }
                                requestInfo.getRequestManager().setMessagecontent("V8尊享卡问题数据：" + mes_sb.toString());
                                return Action.FAILURE_AND_CONTINUE;
                            }
                        }
                    } else {
                        //V8接口返回的Data为空
                        requestInfo.getRequestManager().setMessagecontent("V8接口返回的Data为空");
                        return Action.FAILURE_AND_CONTINUE;
                    }
                    if (StringUtil.isNotNullAndEmpty(message) && "false".equals(result)) {
                        requestInfo.getRequestManager().setMessagecontent(message);
                        return Action.FAILURE_AND_CONTINUE;
                    }
                } else {
                    //V8接口返回空
                    requestInfo.getRequestManager().setMessagecontent("接口返回信息为空,请联系管理员！");
                    return Action.FAILURE_AND_CONTINUE;
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.info("传数据至V8接口异常：" + e.toString());
                requestInfo.getRequestManager().setMessagecontent(e.toString());
                return Action.FAILURE_AND_CONTINUE;
            }
        } else {
            requestInfo.getRequestManager().setMessagecontent("没有可传入V8的数据！");
            return Action.FAILURE_AND_CONTINUE;
        }
        return SUCCESS;
    }
}
